package cn.cellcom.agent.my.simple;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.cellcom.jar.dao.IBaseDao;
import cn.cellcom.jar.dao.IHql;
import cn.cellcom.jar.env.Env;
import cn.cellcom.jar.pagination.PaginationBiz;
import cn.cellcom.jar.reflect.JavaBase;
import cn.cellcom.jar.reflect.JavaBase.GetterOrSetter;
import cn.cellcom.jar.reflect.MethodUtil;
import cn.cellcom.jar.reflect.MethodUtil.AMethod;
import cn.cellcom.jar.util.AU;
import cn.cellcom.jar.util.CopyUtil;
import cn.cellcom.jar.util.IDGenerator;
import cn.cellcom.jar.util.MyException;
import cn.cellcom.jar.util.form.FormUtil;
import cn.cellcom.jar.util.form.FormUtil.SpecialField;
import cn.cellcom.jar.util.form.FormUtil.SpecialValue;

@Controller
@RequestMapping("/mySimple")
public class MySimpleController {

	@Resource
	private PaginationBiz pagination;

	@Autowired
	private IBaseDao dao;

	private org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());

	public static Map<String, String> MAPPER = new HashMap<String, String>();
	static {
		MAPPER.put("student", cn.cellcom.agent.pojo.TStudent.class.getCanonicalName());
	}

	/**
	 * 查询记录
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest req, HttpServletResponse rep) {
		List list = null;
		try {
			final String entityName = req.getParameter("entityName");
			IHql hql = new IHql() {
				@Override
				public Object[] getParaValue(HttpServletRequest req, Object fm) {
					FormUtil fu = new FormUtil();
					try {
						SpecialValue sv = null;
						List inputs = fu.getInput(req, new String[] { "entityName" });
						Object[] obj = fu.valueToList(inputs, sv).toArray();
						return AU.append(obj, new String[] {});
					} catch (MyException e) {
						logger.error("分析获取hql语句失败", e.getException());
						return null;
					}
				}

				@Override
				public String getHql(HttpServletRequest req, Object fm) {
					FormUtil fu = new FormUtil();
					StringBuffer sb = new StringBuffer("from " + MAPPER.get(entityName) + " where 1=1 ");
					SpecialField sf = null;// fu.newSpecialField("agentNickname", "agentNickname", "like");
					try {
						List inputs = fu.getInput(req, new String[] { "entityName" });
						sb.append(fu.fieldToString(inputs, null, null, sf));
					} catch (MyException e) {
						logger.error("", e);
					}
					return sb.toString();
				}
			};
			list = pagination.pagination(null, req, hql).getDataResult();
			req.setAttribute(Env.DATA_NAME, list);
		} catch (MyException e) {
		}
		return new ModelAndView("/test/mySimpleList.jsp");
	}

	@RequestMapping(params = "go")
	public ModelAndView go(HttpServletRequest req, HttpServletResponse rep) {
		String entityName = req.getParameter("entityName");
		String id = req.getParameter("id");
		if (StringUtils.isBlank(entityName) || StringUtils.isBlank(MAPPER.get(entityName))) {
			logger.error("Input entityName[{}] is null", entityName);
			return new ModelAndView("/common/error.jsp");
		}
		if (StringUtils.isBlank(id)) {
			logger.info("Input id is null and show is null, so go to add");
		} else {
			logger.info("Input id[{}] is not null, so go to update ", id);
			Object entity = null;
			try {
				entity = dao.myGet(Class.forName(MAPPER.get(entityName)), id);
			} catch (Exception e) {
				logger.error("", e);
				return new ModelAndView("/common/error.jsp");
			}
			req.setAttribute("entity", entity);
		}
		if (StringUtils.isNotBlank(req.getParameter("showonly"))) {
			logger.info("Input showonly is " + req.getParameter("showonly"));
			req.setAttribute("showonly", "true");
		}
		return new ModelAndView("/test/mySimple.jsp");
	}

	/**
	 * 新增或者修改
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	@RequestMapping(params = "addOrUpdate")
	@ResponseBody
	public MySimpleJson addOrUpdate(HttpServletRequest req, HttpServletResponse rep) {
		String entityName = req.getParameter("entityName");
		String id = req.getParameter("id");
		String idSetter = req.getParameter("idSetter");
		if (StringUtils.isBlank(entityName) || StringUtils.isBlank(MAPPER.get(entityName))
				|| (StringUtils.isBlank(idSetter) && StringUtils.isBlank(id))) {
			logger.error("Input idSetter[{}] or entityName[{}] is null", idSetter, entityName);
			return MySimpleResult.error("传递的参数不完整，请联系管理员");
		}
		try {
			Object entity = null;
			if (StringUtils.isBlank(id)) {// 新增
				entity = Class.forName(MAPPER.get(entityName)).newInstance();
			} else {
				entity = dao.myGet(Class.forName(MAPPER.get(entityName)), id);
			}
			// 请求参数
			CopyUtil.copy(req, entity, null, true);

			if (StringUtils.isBlank(id)) {// 新增
				MethodUtil mu = new MethodUtil();
				AMethod method = mu.newAMethod(JavaBase.toGetterOrSetterName(idSetter, GetterOrSetter.SETTER),
						new Object[] { IDGenerator.getDefaultUUID() });
				mu.invoke(entity, method);
			}
			List list = AU.getNewList(entity);
			dao.mySaveOrUpdate(list);
		} catch (Exception e) {
			logger.error("", e);
			return MySimpleResult.error("操作出现异常，请联系管理员");
		}
		return MySimpleResult.success();
	}

	/**
	 * 查询记录
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	@RequestMapping(params = "delete")
	@ResponseBody
	public MySimpleJson delete(HttpServletRequest req, HttpServletResponse rep) {
		String entityName = req.getParameter("entityName");
		String id = req.getParameter("id");
		if (StringUtils.isBlank(entityName) || StringUtils.isBlank(MAPPER.get(entityName)) || StringUtils.isBlank(id)) {
			logger.error("Input id[{}] or entityName[{}] is null", id, entityName);
			return MySimpleResult.error("传递的参数不完整，请联系管理员");
		}
		try {
			dao.myDelete(Class.forName(MAPPER.get(entityName)), id);
		} catch (Exception e) {
			logger.error("", e);
			return MySimpleResult.error("操作出现异常，请联系管理员");
		}
		MySimpleJson result = MySimpleResult.success();
		result.addAttributes("id", id);
		return result;
	}
}
